package com.nwork.qingmanhua.utils;

import android.text.TextUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * get/set方式获取服务器数据
 */
public class HttpTools {
    private static HttpTools instance = null;
    //设置连接超时的时间
    private static final int CONNECT_TIMEOUT = 10 * 1000;
    //设置读取超时的时间
    private static final int READ_TIMEOUT = 10 * 1000;

    /**
     * 单例获取HttpTools的实例
     *
     * @return
     */
    public static HttpTools getInstance() {
        if (instance == null) {
            instance = new HttpTools();
        }
        return instance;
    }

    public void request(HttpRequest request) {
        if (request != null) {
            request.start();
        }
    }


    /**
     * 从服务器拿到数据回调的接口
     */
    public static interface FetchHttpDataListener {
        public void onFetch(String result);
    }

    /**
     * 通过get/set方式请求服务器数据，并返回
     */
    public static class HttpRequest extends Thread {
        private String mUrlString;
        private boolean mIsPost = false;
        private List<NameValuePair> mParmaList = new ArrayList<NameValuePair>();// post
        // 参数
        private FetchHttpDataListener mListener;

        public HttpRequest(String urlString, FetchHttpDataListener listener) {
            mUrlString = urlString;
            mListener = listener;
        }

        public void setIsPost(boolean isPost) {
            mIsPost = isPost;
        }

        public void setParmaList(List<NameValuePair> parmaList) {
            mParmaList = parmaList;
        }

        /**
         * 调用此方法可以将数据回传
         *
         * @param result
         */
        private void callBack(String result) {
            if (mListener != null) {
                mListener.onFetch(result);
            }
        }

        @Override
        public void run() {
            if (TextUtils.isEmpty(mUrlString)) {
                callBack(null);
                return;
            }

            if (mIsPost) {
                post();
            } else {
                get();
            }

        }

        /**
         * get请求
         */
        private void get() {
            HttpURLConnection conn = null;
            try {
                URL url = new URL(mUrlString);
                conn = (HttpURLConnection) url.openConnection();
                // 设置超时
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(READ_TIMEOUT);
                // 获取响应值
                int status = conn.getResponseCode();
                if (status != HttpStatus.SC_OK) {
                    callBack(null);
                    return;
                }
                // 获取输入流
                InputStream is = conn.getInputStream();
                if (is == null) {
                    callBack(null);
                    return;
                }
                String result = CommonUtils.streamToString(is);
                if (TextUtils.isEmpty(result)) {
                    callBack(null);
                    return;
                }
                callBack(result);
            } catch (Exception e) {
                e.printStackTrace();
                callBack(null);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        /**
         * post请求
         */
        private void post() {
            HttpPost post = null;
            HttpClient client = null;
            try {
                post = new HttpPost(mUrlString);
                // 添加参数
                if (mParmaList != null) {
                    post.setEntity(new UrlEncodedFormEntity(mParmaList,
                            HTTP.UTF_8));
                }
                // 添加超时
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(params,
                        CONNECT_TIMEOUT);
                HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
                client = new DefaultHttpClient(params);
                // 获取响应
                HttpResponse response = client.execute(post);
                // 判断响应值
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    callBack(null);
                    return;
                }
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    callBack(null);
                    return;
                }
                String result = EntityUtils.toString(entity, HTTP.UTF_8);
                if (TextUtils.isEmpty(result)) {
                    callBack(null);
                    return;
                }
                callBack(result);
            } catch (Exception e) {
                e.printStackTrace();
                callBack(null);
            } finally {
                if (post != null) {
                    post.abort();
                }
                if (client != null) {
                    client.getConnectionManager().shutdown();
                }
            }
        }

    }

}
